package tpase.StorageServer.DAO;


import tpase.StorageServer.DO.UserAuth;
import util.JDBCUtil;

import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserAuthDao {
    private String configPath;
    public UserAuthDao(String configPath) {
        this.configPath = configPath;
    }

    public void clearUserAuth() {
        Connection connection = JDBCUtil.getConnect(configPath);
        String sql = "DELETE FROM user_auth";
        PreparedStatement statement = null;
        try {
            statement = connection.prepareCall(sql);
            statement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, statement);
        }
    }

    public void storeUserAuth(UserAuth userAuth) {
        Connection connection = JDBCUtil.getConnect(configPath);
        String sql = "INSERT INTO user_auth (uid, auth) VALUES (?, ?)";
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1, userAuth.getUid());
            statement.setBinaryStream(2, new ByteArrayInputStream(userAuth.getAuth()));
            statement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, statement);
        }
    }

    public UserAuth getUserAuth(String uid) {
        Connection connection = JDBCUtil.getConnect(configPath);
        String sql = "SELECT uid, auth FROM user_auth WHERE uid = ?";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        UserAuth userAuth = null;
        try {
            statement = connection.prepareCall(sql);
            statement.setString(1, uid);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                userAuth = new UserAuth(resultSet.getString("uid"), resultSet.getBytes("auth"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, statement, resultSet);
        }
        if (userAuth == null) {
            System.out.println("getUserAuth, 查询 用户认证信息 不存在");
        }
        return userAuth;
    }

    public static void main(String[] args) {
        UserAuthDao userAuthDao = new UserAuthDao("config/server0/config.properties");
        userAuthDao.clearUserAuth();
        byte[] bytes = {1, 2};
        userAuthDao.storeUserAuth(new UserAuth("11", bytes));
        UserAuth userAuth = userAuthDao.getUserAuth("11");
        System.out.println(userAuth.getUid());
        for (byte b : userAuth.getAuth()) {
            System.out.println(b);
        }
    }
}
